package com.cy.helmet.utils;

import android.os.FileObserver;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

public class RecursiveFileObserver extends Observable {
    private Map<String, SingleFileObserver> paths = new HashMap<>();
    private static RecursiveFileObserver mInstance;
    private Observer observer;

    public static synchronized RecursiveFileObserver getInstance() {
        if (mInstance == null) {
            mInstance = new RecursiveFileObserver();
        }
        return mInstance;
    }

    public void setObserver(Observer observer) {
        this.observer = observer;
        addObserver(observer);
    }

    public void push(String path) {
        if (!paths.containsKey(path)) {
            paths.put(path, new SingleFileObserver(path));
        }
    }

    public void startWatching() {
        Iterator<Map.Entry<String, SingleFileObserver>> entries = paths.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, SingleFileObserver> entry = entries.next();
            entry.getValue().startWatching();
        }

    }

    public void stopWatching() {
        Iterator<Map.Entry<String, SingleFileObserver>> entries = paths.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, SingleFileObserver> entry = entries.next();
            entry.getValue().stopWatching();
        }
    }

    private class SingleFileObserver extends FileObserver {

        protected String mPath;
        protected int mMask;
        public static final int DEFAULT_MASK = CREATE | MODIFY | DELETE;


        public SingleFileObserver(String path) {
            this(path, DEFAULT_MASK);
        }

        public SingleFileObserver(String path, int mask) {
            super(path, mask);
            mPath = path;
            mMask = mask;
        }

        @Override
        public void onEvent(int event, String s) {
            if (observer != null)
                observer.update(mInstance, new FileEvent(event, s));
        }
    }


    public class FileEvent {
        public int event;
        public String fileName;

        public FileEvent(int event, String fileName) {
            this.event = event;
            this.fileName = fileName;
        }
    }
}
